<template>
	<view class="coupon-center">
		<!-- 优惠券列表 -->
		<view class="coupon-list">
			<view class="coupon-item" v-for="(coupon, index) in couponList" :key="coupon.id">
				<!-- 左侧橙色区域 -->
				<view class="coupon-left">
					<view class="discount-value">{{ formatDiscount(coupon) }}</view>
					<view class="min-amount">{{ formatMinAmount(coupon) }}</view>
				</view>
				
				<!-- 右侧白色区域 -->
				<view class="coupon-right">
					<view class="coupon-info">
						<view class="shop-name">{{ coupon.storeName }}</view>
						<view class="valid-date">有效期至: {{ formatDate(coupon.endTime) }}</view>
					</view>
					<view class="claim-btn" @click="coupon.claimed ? useCoupon(coupon) : claimCoupon(coupon)">
						<text class="btn-text">{{ coupon.claimed ? '立即使用' : '点击领取' }}</text>
					</view>
					<!-- 背景水印 -->
					<view class="watermark">券</view>
				</view>
			</view>
		</view>
		
		<!-- 加载状态 -->
		<view v-if="loading" class="loading">
			<text>加载中...</text>
		</view>
		
		<!-- 空状态 -->
		<view v-if="!loading && couponList.length === 0" class="empty-state">
			<text>暂无优惠券</text>
		</view>
	</view>
</template>

<script>
import {
		get,
		post
	} from '@/config/request'
	export default {
		data() {
			return {
				couponList: [],
				loading: false
			}
		},
		methods: {
			async youhuijuan(){
				try {
					this.loading = true;
					const res = await get('/promotion1/lingJuanZhongXin/list', {});
					console.log('优惠券数据:', res);
					
					if (res.code === 200 && res.rows) {
						// 获取用户已领取的优惠券列表
						const claimedRes = await get('/promotion1/userjuan/list', {});
						console.log('已领取优惠券数据:', claimedRes);
						
						// 获取当前用户ID
						const userInfo = uni.getStorageSync('userInfo');
						const currentUserId = userInfo?.memberId;
						console.log('当前用户ID:', currentUserId);
						
						// 提取已领取的优惠券ID列表（需要用户ID和券ID都匹配）
						let claimedCouponIds = [];
						if (claimedRes.code === 200 && claimedRes.rows) {
							claimedCouponIds = claimedRes.rows
								.filter(item => item.memberUserId == currentUserId) // 过滤出当前用户的记录
								.map(item => item.couponId);
						}
						
						// 处理数据，添加claimed字段
						this.couponList = res.rows.map(coupon => ({
							...coupon,
							claimed: claimedCouponIds.includes(coupon.couponId) // 根据数据库查询结果判断是否已领取
						}));
						console.log('处理后的优惠券列表:', this.couponList);
					} else {
						console.error('获取优惠券失败:', res);
						uni.showToast({
							title: '获取优惠券失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('请求优惠券数据出错:', error);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			
			// 格式化优惠券折扣信息
			formatDiscount(coupon) {
				if (coupon.couponName) {
					return coupon.couponName;
				}
				return '优惠券';
			},
			
			// 格式化最低消费金额
			formatMinAmount(coupon) {
				if (coupon.consumeThreshold > 0) {
					return `满${coupon.consumeThreshold}可用`;
				} else {
					return '无门槛';
				}
			},
			
			// 格式化日期
			formatDate(dateString) {
				if (!dateString) return '暂无';
				try {
					const date = new Date(dateString);
					return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
				} catch (error) {
					return '日期格式错误';
				}
			},
			
			async claimCoupon(coupon) {
				if (!coupon.claimed) {
					try {
						// 调用领取优惠券接口
						console.log(coupon)
						// TODO: 从缓存中获取用户ID，若没有则默认为1
						const userInfo = uni.getStorageSync('userInfo') ;
						const memberUserId =userInfo.memberId;
						console.log(userInfo)
						
						// 当前使用默认值1，后续可根据实际需求选择上述方式之一
						// const memberUserId = 1;
						
						const res = await post('/promotion1/userjuan', {
							couponId: coupon.couponId,
							memberUserId: memberUserId,
							status: 0,
							shopId: coupon.shopId
						});
						console.log('领取优惠券响应:', res);
						
						if (res.code === 200) {
							// 领取成功
							coupon.claimed = true;
							uni.showToast({
								title: '领取成功',
								icon: 'success'
							});
							console.log('优惠券领取成功:', coupon);
						} else {
							// 领取失败
							console.error('领取优惠券失败:', res);
							uni.showToast({
								title: res.msg || '领取失败',
								icon: 'none'
							});
						}
					} catch (error) {
						console.error('领取优惠券请求出错:', error);
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						});
					}
				} else {
					uni.showToast({
						title: '已领取过此券',
						icon: 'none'
					});
				}
			},
			
			useCoupon(coupon) {
				uni.showToast({
					title: '正在加载...',
					icon: 'success'
				});
				
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/index/index'
					});
				}, 1500);
			}
		},
		onLoad() {
			this.youhuijuan()
		}
	}
</script>

<style scoped>
	.coupon-center {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding: 20rpx;
	}

	.coupon-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.coupon-item {
		display: flex;
		background-color: #fff;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
		position: relative;
	}

	/* 左侧橙色区域 */
	.coupon-left {
		background: linear-gradient(135deg, #FF6B35, #FF8C42);
		padding: 35rpx 25rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		min-width: 180rpx;
		position: relative;
	}

	.coupon-left::after {
		content: '';
		position: absolute;
		right: -10rpx;
		top: 50%;
		transform: translateY(-50%);
		width: 20rpx;
		height: 20rpx;
		background-color: #f5f5f5;
		border-radius: 50%;
		box-shadow: 0 0 0 4rpx #f5f5f5;
	}

	.discount-value {
		color: #fff;
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 8rpx;
		text-align: center;
		line-height: 1.2;
	}

	.min-amount {
		color: #fff;
		font-size: 22rpx;
		opacity: 0.9;
		text-align: center;
	}

	/* 右侧白色区域 */
	.coupon-right {
		flex: 1;
		padding: 25rpx 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		position: relative;
		background-color: #fff;
	}

	.coupon-info {
		flex: 1;
	}

	.shop-name {
		font-size: 26rpx;
		color: #333;
		margin-bottom: 8rpx;
		font-weight: 500;
	}

	.valid-date {
		font-size: 22rpx;
		color: #666;
	}

	.claim-btn {
		background-color: #ff4444;
		border-radius: 50rpx;
		padding: 12rpx 25rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2rpx 10rpx rgba(255, 68, 68, 0.3);
	}

	.btn-text {
		color: #fff;
		font-size: 22rpx;
		font-weight: 500;
	}

	/* 背景水印 */
	.watermark {
		position: absolute;
		right: 20rpx;
		top: 50%;
		transform: translateY(-50%);
		font-size: 120rpx;
		color: rgba(0, 0, 0, 0.05);
		font-weight: bold;
		z-index: 1;
		pointer-events: none;
	}

	/* 确保按钮在水印之上 */
	.claim-btn {
		position: relative;
		z-index: 2;
	}
	
	/* 加载状态 */
	.loading {
		text-align: center;
		padding: 40rpx;
		color: #666;
	}
	
	/* 空状态 */
	.empty-state {
		text-align: center;
		padding: 80rpx 40rpx;
		color: #999;
		font-size: 28rpx;
	}
</style> 